package com.demo.aop;


import io.undertow.servlet.attribute.ServletRequestAttribute;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;


@Aspect
@Component
public class GlobalRequestLogAspect {

    private final static Logger logger = LoggerFactory.getLogger(GlobalRequestLogAspect.class);

    @Pointcut("execution(public * com.demo.controller.*.*(..) )")
    public void RequestLog(){}

    @Before("RequestLog()")
    public void doBefore(JoinPoint joinPoint){
        //接受到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        logger.info("URI : "+request.getRequestURI().toString() + " (METHOD:"+request.getMethod()+")");
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            logger.info("Parameter name:{},value{}",name, request.getParameter(name));
        }
    }

    /**
     * 后置通知
     * @param obj
     */
    @AfterReturning(returning = "obj", pointcut = "RequestLog()")
    public void doAfterReturning (Object obj) {
        logger.info("RESPONSE : "+obj);
    }

}
